<?php
namespace app\api\controller;

use think\facade\Db;
use think\facade\Request;
use app\common\model\UserSet;
use app\common\model\CardsTransCredit;

/**
 * 2025-02-28 huangzhen
 * 异步处理银1 接收数据
 * Class TimerCards
 * @package app\api\controller
 */
class ActionCdApi
{
    public function __construct()
    {
        $params = Request::param();
        if(empty($params)){
            exit('Welcome to cardEcho bank 1 Api');
        }else{
            $token = $params['token'];
            //4fe1fa0547648373d1bf912546e0da86
            if($token !=md5(md5('cardEcho') . md5(2025))){
                exit('Welcome to cardEcho bank 1 Api !');
            }
        }
    }

    /**
     * 2025-02-28 为新一轮更新，这里存储时is_new=1,默认是0
     * 1.is_new =1 表示最新数据,
     * 2.is_action = 0 新数据 | is_action=1，已处理并成功 |is_action=2 已处理未成功
     */
    public function actionApi()
    {
        $list = Db::name('api_accept_com')
            ->where("is_new =1 and is_action=0")   //2025-02-28 为新一轮更新，这里存储时is_new=1,默认是0
            ->order('id asc')
            ->limit(10)->select()->toArray();
        $ctime      = getUtcTime();
        foreach ($list as $k=>$v){
            $old_id      = $v['id'];
            $user_id     = $v['user_id'];
            $card_num    = $v['card_num'];
            $auth_amount = $v['auth_amount'];
            $post_amount = $v['post_amount'];
            $api_type    = $v['tran_type'];
            $id_match_num= $v['idMatchNumber'];
            $app_code    = $v['app_code'];
            $auth_time   = $v['auth_time'];
            $post_time   = $v['post_time'];
            $reversalFlag= $v['flag'];

            //其他参数
            $api_elements_array = json_decode($v['json_data'] , true);
            $decline_error      = $api_elements_array['correctiveAction'] ?? '';
            $tran_pos_array     = $api_elements_array['pos'] ?? '';
            $shopping           = $tran_pos_array['acceptLocation'] ?? '';
            $mcc                = $api_elements_array['merchant']['mcc'] ?? '';
            $country            = !empty($shopping) ? substr($shopping , -2) : '';
            $currencyCode       = 'USD';

            try {
                $user_list  = Db::name('user')->where(['id'=>$user_id])->find();
                $user_balance = $user_list['balance'];
                $username     = $user_list['username'];

                $user_set   = Db::name('user_set')->where(['user_id'=>$user_id])->find();
                $server_zero_auth = $user_set['zero_auth'] ?? 0.2;
                $server_facebook = $user_set['facebook'] ?? 0.3;
                $server_declined = $user_set['declined'] ?? 0.2;

                $insert_data =[
                    'user_id'       => $user_id,
                    'app_code'      => $app_code,
                    'card_num'      => $card_num,
                    'amount_auth'   => $auth_amount,
                    'amount_post'   => $post_amount,
//                    'reversal_flag' => $reversalFlag,
                    'shopping'      => $shopping,
                    'ctime'         => $auth_time,
                    'bank_type'     => 1,
                    'desc'          => $decline_error,//当状态为DECLINE,这里会有数据，否者为0
                    'idMatchNumber' => $id_match_num,
                    'country'       => $country,
                    'currencyCode'  => $currencyCode,
                ];

                Db::startTrans();
                try {
                    $up_accept_com      = '';
                    $card_list          = Db::name('cards')->where(['card_num' => $card_num])->find();
                    $card_balance_total = $card_list['balance_account'];
                    $card_balance       = $card_list['balance'];
                    $card_status        = $card_list['status'];
                    $card_type          = $card_list['card_type'];
                    //查询接口获取最新卡信息，并更新
                    $get_card_detail = self::getCardDetail($card_list);
                    $error_msg              = '';
                    $get_card_detail_result = $get_card_detail['result'];
                    if($get_card_detail_result){
                        $api_amount         = $get_card_detail['api_amount'];
                        $api_amount_total   = $get_card_detail['api_amount_total'];
                        $card_status        = $get_card_detail['card_status'];
                    }else{
                        $api_amount         = $card_balance;
                        $api_amount_total   = $card_balance_total;
                        $error_msg          = $get_card_detail['error'];
                    }
                    if(substr($api_type , 0 , 13) == 'AUTHORIZATION'
                        || $api_type == 'PRE_AUTHORIZATION')
                    {
                        $is_auth_hand = Db::name('cards_trans')->where([
                            'card_num'      => $card_num,
                            'app_code'      => $app_code,
                        ])->find();
                        if(empty($is_auth_hand)){
                            $insert_data += [
                                'tran_status'   => 'Authorized',
                                'reversal_flag' => $reversalFlag,
                                'utime'         => $auth_time
                            ];
                            Db::name('cards_trans')->save($insert_data);

                            //手机短信0预付
                            if(0 - $auth_amount == 0){
                                $server_amount = $server_zero_auth;
                                $shopping_xx   = strtolower($shopping);
                                if(strstr($shopping_xx , 'facebook') || strstr($shopping_xx , 'facebk')){
                                    $server_amount = $server_facebook;
                                }
                                Db::name('server_cd')->save([
                                    'user_id'       => $user_id,
                                    'type'          => 0,
                                    'card_num'      => $card_num,
                                    'server_amount' => $server_amount,
                                    'ctime'         => $auth_time,
                                    'tran_token'    => $id_match_num,
                                    'shopping'      => $shopping,
                                    'cl_ctime'      => $ctime,
                                    'is_action'     => 0
                                ]);
                            }
                        }

                        //2025-09-11新增预扣时金额=1.95
                        if (strpos(strtolower($shopping), 'google') !== false) {
                            if($auth_amount == '1.95'){
                                Db::name('user_ice_log')->save([
                                    'user_id'   =>  $user_id,
                                    'card_num'  =>  $card_num,
                                    'type'      =>  0,    //0关键字，1超额
                                    'key_name'  =>  'google' . '_1.95',
                                    'amount_auth'   => $auth_amount,
                                    'amount_post'   => $post_amount,
                                    'bank_type'     => 1,
                                    'card_status'   => $card_status,
                                    'ctime'         => $ctime,
                                    'mcc'           => $mcc
                                ]);
                            }
                        }
                        //当发现有大于、等于某个金额M的预授权时，统计这个用户24小时内的预授权总金额，
                        //如果总金额大于、等于N，则冻结这个帐号以及其名下所有的卡，
                        //要求M、N可后台设置，并且可以设置豁免的用户
                        $monitor_tran_auth_amount_user = getSetting('monitor_tran_auth_amount_user');
                        $monitor_user_array = explode(",", $monitor_tran_auth_amount_user);
                        if(!in_array($username, $monitor_user_array)){
                            $monitor_tran_auth_amount = getSetting('monitor_tran_auth_amount');
                            if($auth_amount - $monitor_tran_auth_amount >=0){
                                Db::name('user_ice_log')->save([
                                    'user_id'   =>  $user_id,
                                    'card_num'  =>  $card_num,
                                    'type'      =>  2,    //0关键字，1超额 , 2预扣超额
                                    'amount_auth'   => $auth_amount,
                                    'amount_post'   => $post_amount,
                                    'bank_type'     => 1,
                                    'card_status'   => $card_status,
                                    'ctime'         => $ctime,
                                    'mcc'           => $mcc
                                ]);
                            }
                        }
                    }
                    //授权过期退款
                    else if($api_type == 'EXPIRE'){
                        $is_expire_hand = Db::name('cards_trans')->where([
                            'card_num'      => $card_num,
                            'app_code'      => $app_code,
                        ])->find();
                        if(empty($is_expire_hand)){
                            $insert_data += [
                                'tran_status'   => 'Authorized',
                                'reversal_flag' => $reversalFlag,
                                'utime'         => $post_time,
                            ];
                            Db::name('cards_trans')->save($insert_data);

                        }else{
                            if($is_expire_hand['reversal_flag'] == 'N'){
                                Db::name('cards_trans')
                                    ->where(['id'=>$is_expire_hand['id']])
                                    ->update([
                                        'reversal_flag' => $reversalFlag,
                                        'utime'         => $post_time
                                    ]);

                            }
                        }
                    }
                    else if($api_type == 'REVERSAL')
                    {
                        $reversal_check = Db::name('cards_trans')->where([
                            'card_num'      => $card_num,
                            'app_code'      => $app_code,
                            'tran_status'   => 'Authorized',
                        ])->find();
                        //如果查不到 就插入消费日志，如果有 数组置空 不存储任何数据
                        if(empty($reversal_check)){
                            $insert_data += [
                                'tran_status'   => 'Authorized',
                                'reversal_flag' => $reversalFlag,
                                'utime'         => $post_time,
                            ];
                            Db::name('cards_trans')->save($insert_data);

                        }else{
                            $reversal_flag = $reversal_check['reversal_flag'];
                            $reversal_id   = $reversal_check['id'];
                            if($reversal_flag == 'N'){
                                Db::name('cards_trans')
                                    ->where(['id'=>$reversal_id])
                                    ->update(['reversal_flag' => $reversalFlag]);

                            }
                        }
                    }
                    else if($api_type == 'AUTHORIZED PURCHASE RETURN')
                    {
                        $reversal_check = Db::name('cards_trans')->where([
                            'card_num'      => $card_num,
                            'app_code'      => $app_code,
                            'tran_status'   => 'Authorized',
                        ])->find();
                        //如果查不到 就插入消费日志，如果有 数组置空 不存储任何数据
                        if(empty($reversal_check)){
                            $insert_data += [
                                'tran_status'   => 'Authorized',
                                'reversal_flag' => $reversalFlag,
                                'utime'         => $post_time,
                            ];
                            Db::name('cards_trans')->save($insert_data);

                        }else{
                            $reversal_flag = $reversal_check['reversal_flag'];
                            $reversal_id   = $reversal_check['id'];
                            if($reversal_flag == 'N'){
                                Db::name('cards_trans')
                                    ->where(['id'=>$reversal_id])
                                    ->update([
                                        'reversal_flag' => $reversalFlag,
                                        'utime'         => $post_time
                                    ]);

                            }
                        }
                    }
                    else if($api_type == 'POST'){
                        $post_check = Db::name('cards_trans')->where([
                            'card_num'      => $card_num,
                            'app_code'      => $app_code,
                        ])->find();
                        //如果查不到,说明这个post记录没有,可能是记录漏掉了，那么就插入这条数据
                        if(empty($post_check)){
                            $insert_data += [
                                'tran_status'   => 'Posted',
                                'utime'         => $post_time,
                                'reversal_flag' => 'N'
                            ];
                            Db::name('cards_trans')->save($insert_data);

                        }else{
                            //如果查到，并且状态是Authorized，那么就更新这条记录状态为post,并且更新utime和post金额
                            $status         = $post_check['tran_status'];
                            $post_tran_id   = $post_check['id'];
                            if($status == 'Authorized'){
                                Db::name('cards_trans')
                                    ->where(['id' => $post_tran_id])
                                    ->update([
                                        'tran_status'   => 'Posted',
                                        'amount_post'   => $post_amount,
                                        'utime'         => $post_time,
                                    ]);

                            }
                        }
                        // 银1强制扣款 FORCE POST
                    }
                    else if($api_type == 'FORCE POST'){
                        $insert_data += [
                            'tran_status'   => 'Force Posted',
                            'utime'         => $post_time,
                            'reversal_flag' => $reversalFlag
                        ];
                        Db::name('cards_trans')->save($insert_data);
                        $post_amount = abs($post_amount);
                        $insert_auth = [
                            'user_id'           => $user_id,
                            'tran_status'       => 'FORCE POST',
                            'card_num'          => $card_num,
                            'card_status'       => $card_status,
                            'amount'            => $post_amount,
                            'availableBalance'  => $api_amount,
                            'tran_token'        => $id_match_num,
                            'ctime'             => $post_time,
                            'shopping'          => $shopping,
                            'bank_type'         => 1
                        ];
                        Db::name('cards_trans_fz')->save($insert_auth);

                        //卡已删除,卡总金额是0,发生了强制消费
                        if($card_status == 3 && $api_amount_total == 0){
                            $new_user_balance = $user_balance - $post_amount;
                            Db::name('user')->where(['id'=>$user_id])
                                ->update(['balance'=>$new_user_balance]);
                            Db::name('user_cash_log')->save([
                                'user_id'       => $user_id,
                                'type'          => 1,//debit
                                'action_type'   => 3,//消费
                                'amount'        => $post_amount,
                                'balance'       => $new_user_balance,
                                'desc'          => '消费明细出现异常,已处理异常金额,详情请联系客服',
                                'ctime'         => $ctime
                            ]);
                            EmailSend::sendGridEmail('bank_1_to_amount' , [
                                'email'     => "sensir267@gmail.com",
                                'body'      => "管理员您好，账号:{$username}<br />
                                        被强制扣款,卡号:{$card_num},金额:{$post_amount},<br />
                                        vvacard运营小组<br />",
                                'title'     => "账号({$username}-{$card_num}-{$post_amount}) - 被强制扣款(银1) -- CardEcho",
                            ]);
                            EmailSend::sendGridEmail('bank_1_to_amount' , [
                                'email'     => "897194@gmail.com",
                                'body'      => "管理员您好，账号:{$username}<br />
                                        被强制扣款,卡号:{$card_num},金额:{$post_amount},<br />
                                        vvacard运营小组<br />",
                                'title'     => "账号({$username}-{$card_num}-{$post_amount}) - 被强制扣款(银1) -- CardEcho",
                            ]);
                        }
                    }
                    else if($api_type == 'DECLINE') {
                        //这个ctime 大于 取的时间是最新的时间，因为之前都没记录idMatchNumber,
                        //appcode不靠谱，不唯一,所以 最新的idMatchNumber为参照
                        //如果查不到 就添加这条消费记录即可
                        //DECLINE 和 CREDIT 根据唯一性 查询过库，idMatchNumber是唯一
                        $is_del_hand = Db::name('cards_trans')->where([
                            'card_num'           => $card_num,
                            'tran_status'        => 'Declined',
                            'amount_auth'        => $auth_amount,
                            'idMatchNumber'      => $id_match_num,
                            'ctime'              => $auth_time,
                        ])->find();
                        if(empty($is_del_hand)){
                            $insert_data += [
                                'tran_status'   => 'Declined',
                                'utime'         => $post_time,
                                'reversal_flag' => $reversalFlag,
                            ];
                            Db::name('cards_trans')->save($insert_data);
                            if($shopping != 'Visa Provisioning Service'){
                                $decline_msg = '';
                                $decline_sql = 1; //卡片过期时间错误，请输入正确的过期时间”，且卡片是银行1，预扣款金额是零时，基本上可以判断是撞库
                                $card_num4 = substr($card_num, 0, 6) . ' *** ' . substr($card_num, -4);
                                if ($decline_error == 'EXPIRATION DATE ERROR' || $decline_error == 'VERIFY EXPIRATION DATE OR USE NEW CARD') {
                                    if($auth_amount - 0 !=0){
                                        $decline_sql = 2;
                                        $decline_msg = "我们注意到您的卡片 ({$card_num4}) 由于输入了错误的过期时间导致消费失败，请输入正确的过期时间";
                                    }
                                } else if ($decline_error == 'TRANSACTION AMOUNT LIMIT EXCEEDED' || $decline_error == 'VERIFY AMOUNT AND ADJUST LIMIT') {
                                    $decline_msg = "我们注意到您的卡片 ({$card_num4}) 由于余额不足导致消费失败,请补充余额后再消费,您可以点卡号旁边的‘详情’进入卡片操作页面，增加卡片余额。账户余额和卡片余额是分开的，充值到卡上才能正常消费";
                                } else if ($decline_error == 'VERIFY CVC2 NUMBER ON BACK OF CARD') {
                                    $decline_msg = "我们注意到您的卡片 ({$card_num4}) 由于输入了错误的CVV导致消费失败，请输入正确的CVV";
                                } else if ($decline_error == 'CARD IS NOT ACTIVE' || $decline_error == 'VERIFY CARD STATUS AND ACTIVATE CARD') {
                                    $decline_msg = "我们注意到您的卡片({$card_num4})由于处于冻结状态导致消费失败，请激活后再消费。请在卡列表，冻结再激活该卡. 如果卡片已经删除，请取消您的订阅，防止因发生拒付而产生服务费。";
                                }
                                if (!empty($decline_msg)) {
                                    $email_list = Db::name('api_email')
                                        ->where([
                                            'user_id' => $user_id,
                                            'card_num' => $card_num
                                        ])->order('ctime desc')->find();
                                    $email_ctime = $email_list['ctime'] ?? 0;
                                    //每超过24小时再发送邮件
                                    if ($ctime - $email_ctime > 24 * 60 * 60) {
                                        $username = Db::name('user')->where(['id' => $user_id])->value('username');

                                        $shopping_xx = strtolower($shopping);
                                        if (strstr($shopping_xx, 'facebook') || strstr($shopping_xx, 'facebk')) {
                                            $amount_rate = 0.3;
                                        } else {
                                            $amount_rate = 0.2;
                                        }
                                        DecEmailSend::sendGridDecEmail([
                                            'user_id' => $user_id,
                                            'card_num' => $card_num,
                                            'email' => $username,
                                            'desc' => "{$username} 您好 ; 您有在商户({$shopping})的拒付, 金额为{$auth_amount} , {$decline_msg}",
                                            'amount' => $auth_amount,
                                            'amount_rate' => $amount_rate,
                                            'title' => "您的卡片({$card_num4})有一笔 金额" . $auth_amount . "拒付.请核查拒付原因 -- CardEcho",
                                        ]);
                                    }
                                }
                                if($decline_sql != 2){
                                    //判断是否重复
                                    $check_server = Db::name("server_cd")->where([
                                        'user_id'       => $user_id,
                                        'card_num'      => $card_num,
                                        'tran_token'    => $id_match_num,
                                        'ctime'         => $auth_time,
                                    ])->find();
                                    if(empty($check_server)){
                                        $decline_server = $server_declined;
                                        $decline_type   = 1;
                                        $shopping_xx   = strtolower($shopping);
                                        if(strstr($shopping_xx , 'facebook') || strstr($shopping_xx , 'facebk')){
                                            $decline_server = $server_facebook;
                                            $decline_type   = 2;
                                        }
                                        //2024_12_18拒付新规则:系数(0.2,face0.3) + 拒付金额*1%
                                        $dec_rate = Db::name('user')->where(['id'=>$user_id])->value('dec_rate');
                                        $decline_server = getSprintf($decline_server + round($auth_amount * $dec_rate , 2));

                                        Db::name('server_cd')->save([
                                            'user_id'       => $user_id,
                                            'type'          => $decline_type,
                                            'card_num'      => $card_num,
                                            'tran_amount'   => $auth_amount,
                                            'server_amount' => $decline_server,
                                            'ctime'         => $auth_time,
                                            'tran_token'    => $id_match_num,
                                            'shopping'      => $shopping,
                                            'cl_ctime'      => $ctime,
                                            'is_action'     => 0
                                        ]);
                                    }
                                }
                            }
                        }
                    }
                    else if($api_type == 'CREDIT') {
                        //和 DECLINE 一样 ,因为之前都没记录idMatchNumber,之后会记录
                        //查不到 就添加这条消费记录即可
                        $credit_check = Db::name('cards_trans')->where([
                            'card_num'           => $card_num,
                            'idMatchNumber'      => $id_match_num,
                            'tran_status'        => 'Credit',
                        ])->find();
                        if(empty($credit_check)){
                            $insert_data += [
                                'tran_status' => 'Credit',
                                'reversal_flag' => $reversalFlag,
                                'utime'         => $post_time,
                            ];
                            Db::name('cards_trans')->save($insert_data);

                            $abs_amount = abs($post_amount);
                            $credit_add = [
                                'card_num' => $card_num,
                                'amount' => $abs_amount,
                                'ctime' => $auth_time,
                                'idMatchNumber' => $id_match_num,
                                'user_id' => $user_id,
                                'shopping' => $shopping,
                                'card_status' => $card_status
                            ];

                            if ($card_type == '556766') {
                                //这里的556755的数据库idMatchNumber 记录都有，可以作为唯一性查询
                                $credit_556766_list = Db::name('cards_trans_credit_cd')->where([
                                    'card_num' => $card_num,
                                    'idMatchNumber' => $id_match_num
                                ])->find();
                                if (empty($credit_556766_list)) {
                                    if ($card_status != 3) {
                                        $credit_result = CardsTransCredit::endCredit([
                                            'card_num' => $card_num,
                                            'user_id' => $user_id,
                                            'credit_amount' => $abs_amount,
                                            'shopping' => $shopping,
                                        ], 2);
                                        if ($credit_result) {
                                            $credit_server_set = UserSet::getCardSet($user_id);
                                            $credit_server_set_rate = $credit_server_set[1][$card_type]['rate_refund'];
                                            $credit_server_amount = getSprintf(round($abs_amount * $credit_server_set_rate, 2));
                                            $credit_add += [
                                                'credit_status' => 1,
                                                'utime' => strtotime($post_time),
                                                'server_amount' => $credit_server_amount
                                            ];
                                        }
                                        Db::name('cards_trans_credit_cd')->save($credit_add);
                                    }
                                }
                            } else {
                                Db::name('cards_trans_credit')->save($credit_add);
                            }
                        }

                    }
                    else{
                        Db::name('api_error')->save([
                            'user_id'       => 0,
                            'amount'        => 0.00,
                            'amount_bank'   => 0.00,
                            'type'          => 'unFind_card_status',
                            'data_param'    => "api_type:{$api_type},card_num:{$card_num},time:{$post_time}",
                            'ctime'         => $post_time
                        ]);
                    }

                    Db::name('api_accept_com')->where(['id'=>$old_id])
                        ->update([
                            'is_action'     => 1,
                        ]);

                    Db::commit();
                } catch (\Exception $e) {
                    echo $e->getMessage() . '--' . $e->getLine();
                    Db::name('api_accept_com')->where(['id'=>$old_id])
                        ->update([
                            'is_action'     => 2,
                            'action_error'  => $e->getMessage(),
                        ]);
                    Db::rollback();
                    continue;
                }
            }catch (\Exception $e){
                echo $e->getMessage() . '--' . $e->getLine();
                Db::name('api_accept_com')->where(['id'=>$old_id])
                    ->update([
                        'is_action'     => 2,
                        'action_error'  => $e->getMessage(),
                    ]);
                continue;
            }
        }
    }

    public static function getCardDetail($card_list)
    {
        $card_num           = $card_list['card_num'];
        $card_balance_total = $card_list['balance_account'];
        $card_balance       = $card_list['balance'];
        $card_status        = $card_list['status'];
        $user_id            = $card_list['user_id'];
        $card_type          = $card_list['card_type'];
        $bank_type          = $card_list['bank_type'];
        $check_status       = $card_list['check_status'];

        if ($check_status == 0) {
            return [
                'result'            => false,
                'error'             => 'card no active'
            ];
        }
        $ctime          = getUtcTime();
        $send_param         = [
            "user_id"       => $user_id,
            "action_type"   => 'searchExpDate',
            "card_type"     => $card_type,
            "bank_type"     => $bank_type,
            "post_param"    => [
                "card_num"  => $card_num,
            ]
        ];

        $check_card_api = PublicApi::requestApi('Comdata',$send_param);
        $return_blog    = $check_card_api['blog'];
        $return_list    = $check_card_api['list'];
        if($return_blog){
            $api_amount         = $return_list['cycleAmountLimitAvailable'];
            $api_amount_total   = $return_list['cycleAmountLimit'];

            if(($api_amount_total - $card_balance_total) != 0) {
                $error_type     = 'card_total_comparison';
                Db::name('api_error')->save([
                    'user_id'       => $user_id,
                    'amount'        => $card_balance_total,
                    'amount_bank'   => $api_amount_total,
                    'type'          => $error_type,
                    'data_param'    => json_encode([
                        'card_num'  => $card_num,
                        'balance'   =>$card_balance,
                        'api_balance'=>$api_amount,
                        'balance_account'=>$card_balance_total,
                        'api_balance_account'=>$api_amount_total
                    ]),
                    'ctime'         => $ctime
                ]);
            }
            $api_card_status        = $return_list['cardStatus'];
            $card_update_array      = '';
            if($api_amount - $card_balance != 0){
                $card_update_array      = ['balance' => $api_amount];
            }
            $new_card_status = $card_status;
            $api_card_status_num    = '';
            if($card_status != 3){ //用户已经删除的卡不能同步
                if($api_card_status == 'A'){
                    $api_card_status_num = 1;
                }else if($api_card_status == 'B'){
                    $api_card_status_num = 2;
                }else if($api_card_status == 'F'){
                    $api_card_status_num = 4;
                }
                if(!empty($api_card_status_num)){
                    if($card_status != $api_card_status_num){
                        if(!empty($card_update_array)){
                            $card_update_array += ['status' => $api_card_status_num];
                        }else{
                            $card_update_array = ['status' => $api_card_status_num];
                        }
                    }
                    $new_card_status = $api_card_status_num;
                }
            }
            if(!empty($card_update_array)){
                $re = Db::name('cards')->where(['card_num' => $card_num])->update($card_update_array);
                if($re){
                    if(!empty($api_card_status_num)){
                        if($card_status != $api_card_status_num) {
                            Db::name('user_log')->save([
                                'user_id' => $user_id,
                                'state' => 'update_card_status_api',
                                'ctime' => $ctime,
                                'params' => json_encode([
                                    'card_num' => $card_num,
                                    'old_status' => $card_status,
                                    'new_status' => $api_card_status_num
                                ]),
                                'broswer' => $_SERVER['HTTP_USER_AGENT'] ?? '',
                                'ip' => get_client_ip(0, true)
                            ]);
                        }
                    }
                }
            }
            return [
                'result'            => true,
                'api_amount'        => $api_amount,
                'api_amount_total'  => $api_amount_total,
                'card_status'       => $new_card_status
            ];
        }else{
            return [
                'result'            => false,
                'error'             => 'api request error'
            ];
        }
    }

}
